<template>
	<view>
		<simple-toolbar :title="$t('register.registerAccount')" style="color: #12A234;"></simple-toolbar>
		<el-row type="flex" justify="center">
			<el-col :xs="24" :sm="16" :md="14" :lg="12" :xl="10">
				<view style="padding: 9.37rpx;">
					<view v-if="!registerResult">
						<view class="title align-center">{{ $t('register.title') }}</view>
						<view class="sub-title align-center">{{ $t('register.subTitle') }}</view>
						<el-form class="form" :model="ruleForm" :rules="type == 0 ? rules : rules1" ref="ruleForm"
							label-position="top">
							<el-form-item v-if="type == 1" :label="$t('register.contract_id')" prop="contract_id">
								<el-input v-model="ruleForm.contract_id" :placeholder="$t('register.contract_id_pla')">
								</el-input>
							</el-form-item>
							<el-form-item :label="$t('register.email')" prop="email">
								<el-input v-model="ruleForm.email" :placeholder="$t('register.email_pla')"></el-input>
							</el-form-item>
							<el-form-item :label="$t('register.password')" prop="password">
								<el-input v-model="ruleForm.password" type="password"
									:placeholder="$t('register.password_pla')"></el-input>
							</el-form-item>
							<el-form-item :label="$t('register.affirmPassword')" prop="password2">
								<el-input v-model="ruleForm.password2" type="password"
									:placeholder="$t('register.affirmPassword_pla')" @keyup.enter.native="submitForm()">
								</el-input>
							</el-form-item>
							<view class="note">
								{{ $t('register.note') }}
								<!-- <text class="note-normal">
									点击下面的
								</text>
								<text class="note-strong">
									创建账户
								</text>
								<text class="note-normal">
									按钮，即表示您同意我们的服务条款和隐私声明。
								</text> -->
							</view>
							<el-button
								style="width: 100%; margin: 18.75rpx 0; box-shadow: 0px 3px 6px rgba(18, 162, 52, 0.16);"
								type="primary" @click="submitForm()">{{ $t('register.createAccount') }}</el-button>
							<text>{{ $t('register.text1') }}<text style="color: #12A234; cursor: pointer;"
									@click="login">{{ $t('register.text2') }}</text>{{ $t('register.text3') }}</text>
						</el-form>
					</view>
					<view v-else>
						<view class="title align-center">{{ $t('register.scanning') }}</view>
						<view class="sub-title align-center">
							{{ $t('register.text4') }}
							<text class="text-green">{{ $t('register.text5') }}</text>
						</view>
						<view class="v-box">
							<vue-qrcode :value="registerResult.uri" :options="{ width: 360 }"></vue-qrcode>
						</view>
						<view class="text-green align-center" style="font-size: 6.25rpx;">
							{{ $t('register.saveQrCode') }}
							<image src="../../static/ic_download.png"
								style="margin-left: 2.73rpx;width: 6.79rpx;height: 6.79rpx;"></image>
						</view>
						<view class="h-box justify-center mg-t-base">
							<el-button @click="showPopup">{{ $t('register.nextStep') }}</el-button>
						</view>
					</view>
					<el-dialog :title="$t('auth.chooseAuth')" :visible.sync="dialogAuthTypeVisible"
						:close-on-press-escape="false" :close-on-click-modal="false" :show-close="false"
						:destroy-on-close="true" class="auth">
						<el-radio @change="changeAuthType" v-model="authType" label="2">{{ $t('auth.emailAuth') }}
						</el-radio>
						<el-radio @change="changeAuthType" v-model="authType" label="1">{{ $t('auth.appAuth') }}
						</el-radio>
					</el-dialog>

					<el-dialog :visible.sync="dialogAuthVisible" :close-on-press-escape="false"
						:close-on-click-modal="false" :show-close="false" :destroy-on-close="true" class="authCode">
						<view slot="title">
							<view v-if="authType == 1">{{ $t('auth.enterAppCode') }}</view>
							<view v-else>
								{{ $t('auth.sendCode') }}
								<text class="text-green" v-if="registerResult">{{registerResult.email}}</text>
							</view>
						</view>
						<div class="">
							<div v-if="authType === '2'" class="v-box h-fill">
								<el-input class="input-class" v-model="pin" :placeholder="$t('auth.enterEmailCode')"
									@keyup.enter.native="handleAuth"></el-input>
							</div>
							<div v-else class="h-fill">
								<el-input class="input-class" v-model="pin" :placeholder="$t('auth.enterAppCode')"
									@keyup.enter.native="handleAuth"></el-input>
							</div>
							<view class="h-box justify-end">
								<el-button :disabled="authSuccess" @click="cancelAuth" class="h-fill">
									{{ $t('auth.cancel') }}</el-button>
								<el-button :disabled="authSuccess" @click="handleAuth" type="primary" class="h-fill">
									{{ $t('auth.determine') }}</el-button>
							</view>
						</div>
					</el-dialog>
				</view>
			</el-col>
		</el-row>
	</view>
</template>

<script>
	import {
		registerAdmin,
		register,
		googleAuth,
		emailAuth,
		requestEmailPin
	} from "../../js_sdk/uni-admin/user.js"
	import VueQrcode from '@chenfengyuan/vue-qrcode'
	import {
		mapState,
		mapMutations
	} from "vuex"
	export default {
		components: {
			VueQrcode
		},
		mounted() {
			document.addEventListener('keydown', this.keyDown)
		},
		beforeDestroy() {
			document.removeEventListener('keydown', this.keyDown, false)
		},
		data() {
			var validatePass = (rule, value, callback) => {
				if (value === '') {
					callback(new Error(this.$t('register.password_pla')));
				} else {
					if (this.ruleForm.password !== '') {
						this.$refs.ruleForm.validateField('password2');
					}
					callback();
				}
			};
			var validatePass2 = (rule, value, callback) => {
				if (value === '') {
					callback(new Error(this.$t('register.password_pla2')));
				} else if (value !== this.ruleForm.password) {
					callback(new Error(this.$t('register.password_pla3')));
				} else {
					callback();
				}
			};
			let validateEmail = (rule, value, callback) => {
				if (value === '') {
					callback(new Error(this.$t('register.email_pla')));
				} else {
					callback();
				}
			}
			let validateContractId = (rule, value, callback) => {
				if (value === '') {
					callback(new Error(this.$t('register.contract_id_pla')));
				} else {
					callback();
				}
			}
			return {
				type: 1,
				ruleForm: {
					contract_id: '',
					email: uni.getStorageSync('email') || '',
					password: '',
					password2: ''
				},
				rules: {
					email: [{
						required: true,
						// message: this.$t('register.email_pla'),
						validator: validateEmail,
						trigger: 'blur'
					}],
					password: [{
						required: true,
						validator: validatePass,
						trigger: 'blur'
					}],
					password2: [{
						required: true,
						validator: validatePass2,
						trigger: 'blur'
					}]
				},
				rules1: {
					contract_id: [{
						required: true,
						// message: this.$t('register.contract_id_pla'),
						validator: validateContractId,
						trigger: 'blur'
					}],
					email: [{
						required: true,
						// message: this.$t('register.email_pla'),
						validator: validateEmail,
						trigger: 'blur'
					}],
					password: [{
						required: true,
						validator: validatePass,
						trigger: 'blur'
					}],
					password2: [{
						required: true,
						validator: validatePass2,
						trigger: 'blur'
					}]
				},
				registerResult: null,
				dialogAuthTypeVisible: false,
				dialogAuthVisible: false,
				authType: '',
				pin: '',
				authSuccess: false
			}
		},
		onLoad(e) {
			if (e.type) {
				this.type = e.type
			}
		},
		methods: {
			...mapMutations("user", ["SET_TOKEN", "SET_USER_INFO"]),
			keyDown(e) {
				// console.log(e);
				if (e.keyCode == 13) {
					this.submitForm()
				}
			},
			login() {
				uni.redirectTo({
					url: "./login"
				})
			},
			async changeAuthType(type) {
				if (type == '2') {
					try {
						await requestEmailPin({
							user_id: this.registerResult.user_id
						})
						this.dialogAuthTypeVisible = false
						this.dialogAuthVisible = true
					} catch (e) {
						console.error(e)
					}
				} else {
					this.dialogAuthTypeVisible = false
					this.dialogAuthVisible = true
				}
			},
			showPopup() {
				this.dialogAuthTypeVisible = true
			},
			submitForm() {
				this.$refs.ruleForm.validate(async (valid) => {
					if (valid) {
						try {
							let res = undefined
							if (this.type == 0) { // 管理员
								res = await registerAdmin({
									email: this.ruleForm.email,
									password: this.ruleForm.password,
									password2: this.ruleForm.password2
								})
							} else { // 普通用户
								let data = {
									contract_num: this.ruleForm.contract_id,
									email: this.ruleForm.email,
									password: this.ruleForm.password,
									password2: this.ruleForm.password2
								}
								res = await register(data)
							}

							uni.setStorageSync('email', this.ruleForm.email)
							this.registerResult = res.data
						} catch (e) {
							console.error(e)
						}
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			cancelAuth() {
				this.dialogAuthVisible = false
				this.authType = ''
			},
			async handleAuth() {
				if (!this.pin.trim()) {
					this.$message.error(this.$t('global.enterVerificationCode'))
					return
				}
				try {
					let res
					if (this.authType === '1') {
						res = await googleAuth({
							user_id: this.registerResult.user_id,
							pin: this.pin
						})
					} else {
						res = await emailAuth({
							user_id: this.registerResult.user_id,
							pin: this.pin
						})
					}
					this.SET_TOKEN({
						token: res.data.token
					})
					this.SET_USER_INFO(res.data)
					this.$message.success(this.$t('global.verificationBy'))
					this.authSuccess = true
					setTimeout(() => {
						uni.reLaunch({
							url: "../index/statisics"
						})
					}, 1000)
				} catch (e) {
					//TODO handle the exception
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.form /deep/ {
		.el-form-item {
			margin: 0 0 6.25rpx 0;
		}

		.el-form-item:first-child {
			margin-top: 15.62rpx;
		}

		.el-form-item__label {
			padding: 0;
			line-height: 11.71rpx;
		}
	}

	.title {
		font-size: 12.5rpx;
		font-family: Source Han Sans SC;
		font-weight: 800;
		line-height: 18.35rpx;
		color: #3B3E66;
		margin-top: 18.75rpx;
	}

	.sub-title {
		font-size: 7.03rpx;
		font-family: Source Han Sans SC;
		font-weight: 400;
		line-height: 10.54rpx;
		color: #9D9EB2;
	}

	.note {
		font-size: 7.03rpx;
		line-height: 10.54rpx;
		color: #3B3E66;

		&-normal {}

		&-stong {
			font-weight: 400;
		}
	}
</style>
